//package com.gitee.mazhenggg.demo.gateway.filter;
//
//import com.gitee.mazhenggg.demo.gateway.service.AuthService;
//import io.opentelemetry.api.OpenTelemetry;
//import io.opentelemetry.api.trace.Span;
//import io.opentelemetry.api.trace.SpanKind;
//import io.opentelemetry.api.trace.Tracer;
//import io.opentelemetry.context.Context;
//import io.opentelemetry.context.Scope;
//import io.opentelemetry.context.propagation.TextMapPropagator;
//import io.opentelemetry.semconv.trace.attributes.SemanticAttributes;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
//import org.springframework.core.env.Environment;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//
//import java.net.URI;
//
//@Slf4j
//public class TraceFilter implements GlobalFilter {
//
//    @Autowired
//    private OpenTelemetry openTelemetry;
//
//    @Value("${spring.application.name}")
//    private String applicationName;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain gatewayFilterChain) {
//        Span span = getClientSpan(openTelemetry.getTracer(applicationName), exchange);
//        Scope scope = span.makeCurrent();
//        inject(exchange);
//        return gatewayFilterChain.filter(exchange)
//                .then(Mono.fromRunnable(() -> {
//                            scope.close();
//                            span.end();
//                        })
//                );
//    }
//
//    private void inject(ServerWebExchange serverWebExchange) {
//        HttpHeaders httpHeaders = new HttpHeaders();
//        TextMapPropagator textMapPropagator = openTelemetry.getPropagators().getTextMapPropagator();
//        textMapPropagator.inject(Context.current(), httpHeaders, HttpHeaders::add);
//        ServerHttpRequest request = serverWebExchange.getRequest().mutate()
//                .headers(headers -> headers.addAll(httpHeaders))
//                .build();
//        serverWebExchange.mutate().request(request).build();
//    }
//
//    private Span getClientSpan(Tracer tracer, ServerWebExchange serverWebExchange) {
//        ServerHttpRequest serverHttpRequest = serverWebExchange.getRequest();
//        URI routeUri = serverWebExchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
//        return tracer.spanBuilder(routeUri.getPath()).setSpanKind(SpanKind.CLIENT).setAttribute(SemanticAttributes.HTTP_METHOD, serverHttpRequest.getMethod().name()).startSpan();
//    }
//
//}
